package drafts_config

import (
	"news_for_deepseek_interface/controller"
	"news_for_deepseek_interface/model"
	"news_for_deepseek_interface/model/drafts"
	"time"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

// 定时生成文章
func CrontabCreateNews(c *gin.Context) {
	db := model.GetInstance().GetDB()

	var config drafts.DraftsConfigModel
	if err := db.Model(&drafts.DraftsConfigModel{}).
		Where("id = ?", 1).
		Find(&config).Error; err != nil {
		controller.Fail(c, controller.BusinessError, "查询配置失败")
		return
	}

	// 判断是否是整点
	if config.HourFormat != time.Now().Hour() {
		controller.Success(c, "未到执行时间")
		return
	}

	//查询记录
	var logs drafts.DraftsLogsModel
	if err := db.Model(&drafts.DraftsLogsModel{}).
		Where("date = ?", time.Now().Format("2006-01-02")).
		Where("type = ?", 1).
		Find(&logs).Error; err != nil {
		if err != gorm.ErrRecordNotFound {
			controller.Fail(c, controller.BusinessError, "查询记录失败")
			return
		}
	}

	if logs.Id > 0 {
		controller.Success(c, "今天已经生成过了")
		return
	}

	produceNewsMessage := &ProduceNewsMessage{
		KeepTitle:          config.KeepTitle,
		KeepContent:        config.KeepContent,
		TypeClassifyId:     config.TypeClassifyId,
		BusinessClassifyId: config.BusinessClassifyId,
		StartId:            config.StartId,
		Number:             config.Number,
		Type:               1,
	}

	if err := produceNewsMessage.GenerateNews(); err != nil {
		controller.Fail(c, controller.BusinessError, "生成文章失败")
		return
	}

	controller.Success(c, "生成文章成功")
}
